﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using System.Net;
using System.Xml.XPath;
using System.IO;
using System.Diagnostics;
namespace Analyze
{
    public class DocumentReader
    {
        Parser _parser;
       // public delegate void DoneFetching(List<string> data);
      //  public event DoneFetching doneFetching;
        
        private HtmlAgilityPack.HtmlDocument _document;
        private string _søgeStreng;
        private List<HtmlNode> _objects = new List<HtmlNode>();
        private StreamReader _reader;

        #region Properties

        public List<HtmlNode> Objects
        {
            get { return _objects; }
        }
        #endregion

        public DocumentReader(string søgStreng)
        {
            _parser = new Parser();
            this._søgeStreng = søgStreng;
            ReadHtml(_søgeStreng);
        }
        


        void CreateHtmlDocument(TextReader reader)
        {
          
            
        }

        public void FetchHtml(int songs, int startpoint)
        {
            Console.WriteLine("Fecthing....");
            try
            {
                for (int i = startpoint; i < songs; i++)
                {

                    HtmlNode foos = _document.DocumentNode.SelectSingleNode("//div[@class='show" + i.ToString() + "']");
                    if (foos == null)
                    {
                        songs = 0;
                        Console.WriteLine("Stopped");

                    }
                    else
                    {
                       
                        Objects.Add(foos);

                    }

                }
                //if (doneFetching != null)
                //{
                //    doneFetching(_objects);
                //}
                _parser.Objects = _objects;
                _parser.ParseLinks();
                
                
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.Message);
            }
           

               
        }

        private void ReadHtml(string søgeStreng)
        {
            WebClient wclient = new WebClient();
            wclient.OpenReadCompleted += new OpenReadCompletedEventHandler(wclient_OpenReadCompleted);
            wclient.OpenReadAsync(new Uri("http://mp3skull.com/mp3/"+ søgeStreng + ".html", UriKind.Absolute),null);
         
          
          
        }

        void wclient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
           
            _document = new HtmlAgilityPack.HtmlDocument();
            _document.Load(e.Result);
            FetchHtml(10, 1);
        }
    }
}
